// permission.entity.ts
import {
  Column,
  Entity,
  JoinTable,
  ManyToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Role } from '@/role/entities/role.entity';
import { PermissionApi } from '@/permission/entities/permission-api.entity';

@Entity()
export class Permission {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  code: string;

  @Column({
    nullable: true,
  })
  parentId: number = 0;

  @Column({
    nullable: true,
  })
  type: string;

  // 加入一个多对多的关系, 用于关联角色
  @ManyToMany(() => Role, (role) => role.permissions)
  @JoinTable({
    name: 'role_permission',
    joinColumn: {
      name: 'permission_id',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'role_id',
      referencedColumnName: 'id',
    },
  })
  roles: Role[];

  @OneToOne(() => PermissionApi, (permissionApi) => permissionApi.permission, {
    cascade: true,
  })
  permissionApi: PermissionApi;
}
